package com.tengju.user.infrastructure.shared;

import com.obs.services.ObsClient;
import com.obs.services.model.AccessControlList;
import com.obs.services.model.DeleteObjectRequest;
import com.obs.services.model.DeleteObjectResult;
import com.obs.services.model.PutObjectResult;
import com.tengju.user.domain.model.user.UserId;
import com.tengju.user.domain.shared.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;

@Slf4j
public class HuaweiObsUtil {

    private final static String ACCESS_KEY_ID =  "SCDZBWTDNMGFJRPVLIWS";

    private final static String SECRET_ACCESS_KEY =  "PgjuF3AG7G1SADquj7jLBV8Pwl1IybNICdWcJv8k";

    private final static String END_POINT = "obs.cn-east-3.myhuaweicloud.com";

    private final static String BUCKET_NAME = "dt-data";

    public static String fileUpload(String objectKey, InputStream inputStream) {
        try {
            // 创建ObsClient实例
            ObsClient obsClient = new ObsClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, END_POINT);
            //上传
            PutObjectResult putObjectResult = obsClient.putObject(BUCKET_NAME, objectKey, inputStream);
            //权限设置
            obsClient.setObjectAcl(BUCKET_NAME,objectKey, AccessControlList.REST_CANNED_PUBLIC_READ);

            inputStream.close();
            obsClient.close();
            return putObjectResult.getObjectUrl();
        } catch (Exception e) {
            log.error("{}文件上传失败！",objectKey);
        }
        return null;
    }


    public static void main(String[] args) throws IOException {

        //读取本地图片输入流
        File file = new File("/Users/wuziyang/test.png");

        byte[] bytes = Files.readAllBytes(file.toPath());

        MultipartFile multipartFile = new MultipartFile() {
            @Override
            public String getName() {
                return "aaaaaaa";
            }

            @Override
            public String getOriginalFilename() {
                return "test1.png";
            }

            @Override
            public String getContentType() {
                return "multipart/form-data";
            }

            @Override
            public boolean isEmpty() {
                return false;
            }

            @Override
            public long getSize() {
                return 0;
            }

            @Override
            public byte[] getBytes() throws IOException {
                return bytes;
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(bytes);
            }

            @Override
            public void transferTo(File dest) throws IOException, IllegalStateException {

            }
        };
        fileUpload(multipartFile.getOriginalFilename(),multipartFile.getInputStream());
    }

}
